package org.example;

import java.util.concurrent.atomic.AtomicInteger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.policy.MaxAttemptsRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Title : RetryController
 * @Description: :
 * @author: libo@juzishuke.com
 * @date: 2023/10/19 16:37
 * @Version:1.0
 */
@Slf4j
@RestController
@RequestMapping("retry")
public class RetryController {

    @Autowired
    private RetryTemplate template;

    @GetMapping("echo2")
    public boolean echo2() {
        boolean isDone = false;
        try {
            template.setRetryPolicy(new MaxAttemptsRetryPolicy(5));
            ai = new AtomicInteger(0);
            isDone = template.execute(ctx -> {
                log.info("retryCount :{}", ctx.getRetryCount());
                doRetry(true);
                return null;
            }, ctx -> {
                doRecover(true);
                return null;
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return isDone;
    }

    private AtomicInteger ai = new AtomicInteger(0);

    public boolean doRetry(boolean isRetry) {
        ai.addAndGet(1);
        log.info("开始通知下游系统 : {}", ai);
        log.info("通知下游系统");
        if (isRetry) {
            throw new RuntimeException("通知下游系统异常");
        }
        return true;
    }

    public boolean doRecover(boolean isRetry) {
        log.info("recover");
        return false;
    }
}
